﻿import { observable, action,toJS } from 'mobx';
import { Base64 } from 'js-base64';

import { Tools, Modal, Toast,ActionSheet, WingBlank, WhiteSpace, Button } from 'weaver-mobile';
import { Reply, Comment, CKRichText,Browser,RouteLayout,MapPage  } from 'weaver-mobile-page';

import * as Api from '../../api/MyBlogApi';
import * as WriteApi from '../../api/BlogWriteApi';
import WeaUtils from "../../public/wea-utils";

const alert = Modal.alert;
const getLabel = Tools.getLabel;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let wrapProps;
if (isIPhone) {
    wrapProps = {
        onTouchStart: e => e.preventDefault(),
    };
}
export default class BlogCommentStore {
  
  constructor(params) {
    if (params && params.getComment) {
      this.blogCommentStore =  new Comment.Store({   // 我的微博-微博
        getComment: params.getComment,
        operate: this.operateBlog,
      });
    }
  }

    @observable disscussShareLayout = new RouteLayout.Store({ route: '/myBlog/writeBlog/discussShareTool' });
    @observable disscussShareLayoutTwo = new RouteLayout.Store({ route: '/myBlog/blog/writeMyBlog/discussShareTool' });

    @observable cusHrmLayout = new RouteLayout.Store({ route: '/myBlog/writeBlog/discussShareTool/cusHrm' });
    @observable mapPage = new MapPage.Store({ route: '/map-page/demo-1' });

  @observable isBlogNote= 0;
  @observable userid = null;
  @observable workdate = null;
  @observable blogText = null;  // 写微博页面内容渲染
  @observable optionId = null; // 当前点击事件的replyId
  @observable reply = new Reply.Store({ getAttachList: this.getReplyAttachList ,getAtConfig: this.getAtConfig});
  @observable replyVisible = false;
  @observable replyComment = null;
  @observable replyCommentParent = null;
  @observable commentReplyStoreMap = {};

  @observable toWriteBlog = null;
  @observable showReply = null;
  @observable isNoTip =false;
  /* 写微博 */
  @observable type = null; // 添加，1补交，2编辑
  @observable discussId = null;

  @observable blogCommentStore = null;
  @observable writeReply = null;
  @observable routePath = null;



  @observable templateBrowser = new Browser.Store({ route: '/myBlog/discussShareTool/browser/template' });

  @observable ecmeReply = new Reply.Store({ getAttachList: this.getAttachListEcme});

  @observable isDraft = true; //是草稿还是便签
  @observable blognotes = ''; //是草稿还是便签
  @observable notetiming = "0"; //是否开启微博草稿定时保存notetiming
  @observable notetime = 0; // 定时保存草稿时间

setIsNoTip = (val) =>{
    this.isNoTip=val;
 }
setBlogNote = (val) => {
  this.isBlogNote=val;
}


@observable hasMood = false;


 getFakePromise = () => {
     const attachList = []
     const mood = {
         key:'mood',
         type:'custom',
         config:{
             onClick:this.changeEcmeMood
         },
         iconType: 'note',
         iconBgColor: '#245c71',
         text: '高新'

     }
     attachList.push(mood);
     var p = new Promise(function(resolve, reject){
             resolve(attachList);
     });
     return p;
 }


    getAttachListEcme = (params) => {
        const attachList = []
        const mood = {
            key:'mood',
            type:'custom',
            config:{
                onClick:this.changeEcmeMood
            },
            iconType: 'blog-biaoqing',
            iconBgColor: '#245c71',
            text: '高兴'

        }





        return WriteApi.getBlogAppList(params).then(res=>{
            res.attachList = [];
            res.attachList.push({
                config: {isSingle: true, hasAdvanceSerach: true, type: "mobileblogtemplate"},
                iconBgColor: "#F3B04C",
                iconType: "template",
                key: "template",
                model: 2,
                path:window.location.href.indexOf('/myBlog/writeBlog')>0? "/myBlog/writeBlog/browser":"/myBlog/blog/writeMyBlog/browser",
                text: "模板",
                type: "browser",
            });
            if(res.mood=='1'){
                res.attachList.unshift(mood);
            }
            return res;
        });

    }



  // 模拟数据 -- 走接口
  getAttachListTest = () => {
    const attachList = [
      {
        key: 'flow', // 字符串
        type: 'browser',
        path: '/myBlog/blog/writeMyBlog/browser',
        config: {
          type: 16,
          isSingle: false,
          hasAdvanceSerach: true,
        },
        iconType: 'flow',
        iconBgColor: '#61A8F5',
        text: '流程',
        model: 2, // model(模式) 1: 常规模式， 2: 编辑模式（不显示小红点）
      },
      {
        key: 'doc',
        type: 'browser',
        path: '/myBlog/writeBlog/browser',
        config: {
          type: 9,
          isSingle: false,
        },
        iconType: 'file',
        iconBgColor: '#F3B04C',
        text: '文档',
        model: 2,
      },
      {
        key: 'file',
        type: 'upload',
        path: '/myBlog/blog/writeMyBlog/upload',
        config: {
          multiSelection: true,
        },
        iconType: 'file',
        iconBgColor: '#F3B04C',
        text: '附件',
        model: 2,
      },
    ];
    return attachList;
  }

  // 模拟数据 -- 走接口
  getAtConfigTest = () => {
    const atConfig = {
      key: 'at',
      path: '/myBlog/blog/writeMyBlog',
      config: {
        type: 16,
        isSingle: false,
      },
    };
    return atConfig;
  }

  @action
  setRoutePath = (pathname) => {
    this.routePath = pathname;
  }

  @action
  setReplyConfig = () => {
    //this.writeReply = new Reply.Store({ getAttachList: this.getAttachList, getAtConfig: this.getAtConfig});
    this.writeReply = new CKRichText.Store({reply:{ getAttachList: this.getAttachList, getAtConfig: this.getAtConfig}});

  }


    @observable moodd = '1';



    @action
    changeEcmeMood = () => {


    let attachlist = toJS(this.ecmeReply.attachList);

        toJS(this.ecmeReply.attachList).map((item,index) => {

           if(item.key=='mood'){
               if(this.moodd=='1'){
                   this.moodd='0'
                   attachlist[index].iconType='blog-bugaoxing'
                   attachlist[index].text="不开心";
               }else{
                   this.moodd='1'
                   attachlist[index].iconType='blog-biaoqing'
                   attachlist[index].text="开心";
               }
           }
        })
        this.ecmeReply.setState({attachList:attachlist});
    }

    @action
    changeMood = () => {
        let writeAttachList = toJS(this.writeReply.replyStore.attachList);
         let mood = this.moodd;
        toJS(this.writeReply.replyStore.attachList).map((item,index) => {

            if(item.key=='mood'){
                if(mood=='1'){
                    this.moodd='0'
                    writeAttachList[index].iconType='blog-bugaoxing'
                    writeAttachList[index].text="不开心";
                }else{
                    this.moodd='1'
                    writeAttachList[index].iconType='blog-biaoqing'
                    writeAttachList[index].text="开心";
                }
            }
        })
        this.writeReply.replyStore.setState({attachList:writeAttachList})
    }

    @action
    getAttachList = () => {
        let params = {routePath: this.routePath};
        return WriteApi.getBlogAppList(params).then(res=>{

            const blogNote={
                key: 'blogNote',
                type: 'custom',
                config: {
                    onClick:this.blogNoteDemo
                },
                iconType: 'note',
                iconBgColor: '#245c71',
                text: getLabel(33305,'便签')
            }


            const mood = {
                key:'mood',
                type:'custom',
                config:{
                    onClick:this.changeMood
                },
                iconType: 'blog-biaoqing',
                iconBgColor: '#245c71',
                text: '高兴'

            }

            if(this.routePath=='/myBlog/writeBlogNote'){

            }else{
                res.attachList.unshift(blogNote);
                if(res.mood=='1'){
                    res.attachList.unshift(mood);
                }

            }

            return res;
        });
    }

  getAtConfig = () => {
    return new Promise((resolve) => {
      resolve({
        atConfig: {
          key: 'at',
          path: this.routePath,
          config: {
            type: 1,
            isSingle: false,
            hasAdvanceSerach: true
          },
        },
      });
    })

  }



    getBlogNoteEcmeinfo = (params,callback) => {
        return WriteApi.getBlogNoteEcmeinfo(params).then(res => {
           if(callback)callback(res);
        })
    }


    @action('操作的判断')
  operateBlog = (params) => {
    
    const {type, data, parent} = params;

    this.replyComment = data;
    this.replyCommentParent = parent;
    if (data) {
      this.userid = data.userid;
      this.workdate = data.workdate;
      this.optionId = data.replyId.indexOf('==') !== -1 ? '' : data.replyId;
    }

    if (type.type === 'blog-comment') {
      if (!this.commentReplyStoreMap[data.replyId]) {
        this.commentReplyStoreMap[data.replyId] = new Reply.Store({ getAttachList: this.getReplyAttachList });
      }
      this.showReply(true);
    }else if(type.type === 'blog-fuzhi'){
        var textField= document.getElementById(data.replyId).querySelector(".wm-comment-content-msg")
          if (document.body.createTextRange) {
            var range = document.body.createTextRange();
            range.moveToElementText(textField);
            range.select();
            //message.success('微博内容已复制到剪切板');
        } else if (window.getSelection) {
            var selection = window.getSelection();
            var range = document.createRange();
            range.selectNodeContents(textField);
            selection.removeAllRanges();
            selection.addRange(range);
        } else {
           console.log('none')
        }
        Toast.info(getLabel(515358 ,'微博内容已复制到剪切板'), 1);
        document.execCommand('copy')
    } 
    else if (type.type === 'delete') {
      alert(getLabel(388758, '确认要删除吗？'),'', [
        { text: getLabel(31129, '取消') },
        {
          text: getLabel(33703, '确认'),
          onPress: () => {
            let params = {
              replyId: data.replyId,
              workdate: data.workdate
            }
            if (parent && parent.replyId.indexOf('==') === -1) {
              params.discussId=parent.replyId;
            }
            return Api.deleteBlogReplay(params).then(res => {
              this.blogCommentStore.doOperateReply({
                replyId: data.replyId,
                parentId: parent ? parent.replyId : '',
                reply:this.replyCommentParent ? res.replyList[0].childReply : res.replyList[0]
              })
            })
          }
        },
      ])
    } else if (type.type === 'fabulous') {
      let params = {
        discussId: this.optionId,
        userId: data.userid,
        optType: data.isPraise ? 0 : 1,
        workdate: data.workdate,
      }
      return Api.addOrDeleteZan(params).then(res => {
          this.blogCommentStore.doOperateReply({
          replyId: data.replyId,
          reply: res.replyList[0]
        })
      })
    } else if (type.type === 'bianji') {
      if (data.content !== '') {

        this.setType('2');
         this.setBlogNote(0);
          this.getBlogById({uid: data.userid, discussId: this.optionId},(res11)=>{
                 this.blogText = res11;
                 this.toWriteBlog();
          })
      } else {
           this.setBlogNote(1);
        this.setType('3');
        this.toWriteBlog();
      
      }
    } else if (type.type === 'blog-fill') { // 提醒操作
      let params = {
        workdate: data.workdate,
        remindId: data.userid
      }
      Api.sendRemindUnsubmit(params).then(res=>{
        res.status === '1' && Toast.info(getLabel('384538',"已发送提醒"), 1);
      })
    }
  }

  @action('回复组件的显隐')
  setReplyVisible = (v) => {
    this.showReply = v;
  }

  @action('评论提交事件')
  saveComment = (datas,callback) => {


    let dataId =  this.replyComment.replyId;
    let params = {
      content: datas.text,
      commentType: datas.checked ? 1 : 0,
      workdate: this.replyComment.workdate,
      bediscussantId: this.replyCommentParent ? this.replyCommentParent.userid :this.replyComment.userid,
      comefrom: 4,
     discussId: dataId
    }
    if (this.commentReplyStoreMap[dataId]) {
      this.commentReplyStoreMap[dataId].doClear();
    }
    if (this.replyCommentParent) {
      params.replyId = this.replyComment.replyId;
      params.relatedId =  this.replyComment.userid;
    }

    

    if (Array.isArray(datas.imgList)) {
      params.content += datas.imgList.map((img) => {
        return "<img  class='imgSrc' style='max-width: 220px' src='"+img.imgSrc+"'/>";
      }).join();
    }
   
    return Api.addBlogReply(params).then(res=>{
      if (res.status === '1') {
        if (this.replyComment) {
          this.blogCommentStore.doOperateReply({
            replyId: dataId,
            parentId: this.replyCommentParent ? this.replyCommentParent.replyId : '',
            reply: this.replyCommentParent ? res.replyList[0].childReply : res.replyList[0],
          })
        } else {
          this.blogCommentStore.getDatas();
        }
      }
      this.showReply(false);
      if(callback) callback();
    })
    
  }




    showActionSheet = () => {

        const BUTTONS = [];
        toJS(this.ecmeEditButtons).map((item,key) =>{
            let it ={};
            let text=  '内容'+key+' '+item.dateandtime;

            BUTTONS.push({
                content: text,
                onClick: () =>{
                    this.getBlogEcmeInfo({blogid:item.id,partid:item.partid},(res) => {
                        this.discussId = item.id;
                        this.partid = item.partid;
                        console.log(item.partid);
                        if(item.partid==0){
                            this.blogText = res.content;
                        }
                        this.toWriteBlog();
                    })
                },
            })

        })
        BUTTONS.push({
            content: "取消",
            onClick: () => console.log('Cancel'),
        })


        ActionSheet.showActionSheetWithOptions({
                options: BUTTONS,
                cancelButtonIndex: BUTTONS.length - 1,
                // destructiveButtonIndex: BUTTONS.length - 2,
                // title: 'title',
                // message: 'I am description, description, description',
                maskClosable: true,
                'data-seed': 'logId',
                wrapProps,
            },
            (buttonIndex) => {
            this.clicked = BUTTONS[buttonIndex];
            });
    }

    clicked= 'none';

    @action
  setToWriteBlog = (val) => {
    this.toWriteBlog = val;
  }

  getReplyAttachList = () => {

    //const attachList = [];
    //return attachList;
    //组件修改成返回promise,此处暂时改成请求一个空请求
    return new Promise((resolve) => resolve({
      attachList:[]
    })) 
  }

  /************** 写微博 ****************/
  @action('获取富文本内容 老逻辑根据工作日')
  getBlogByUserDate = (params,callback) => {
    let pramas = {
      userId: params.uid,
      workdate: params.workdate
    }
    WriteApi.getBlogByUserDate(pramas).then(data=>{
      this.blogText = Base64.decode(data.discussVo.content);
      this.workdate = data.discussVo.workdate;
      this.discussId = data.discussVo.id;
      if (callback) callback(Base64.decode(data.discussVo.content));
    })
  }

  @observable
  partid = 0;

  @observable
  ecmeEditButtons=[];


    @action('获取富文本内容 新逻辑根据微博id')
    getBlogById = (params,callback) => {
        WriteApi.getBlogById(params).then(data=>{
            this.blogText = Base64.decode(data.discussVo.content);
            this.workdate = data.discussVo.workdate;
            this.discussId = data.discussVo.id;
            this.partid = data.discussVo.partid;
            this.ecmeEditButtons=data.discussVo.ecmeEditButtons;
            if(data.discussVo.appItems[0]&&data.discussVo.appItems[0].value=='4'){
                this.moodd='1';
            }else if(data.discussVo.appItems[0]&&data.discussVo.appItems[0].value=='2'){
                this.moodd='0';
            }

            if (callback) callback(Base64.decode(data.discussVo.content));
        })
    }





    @action('富文本内容更改触发方法')
  setBlogText = (val) => {
    this.blogText = val;
  }

  // 添加、补交、编辑判断
  setType = (val) => {
    this.type = val;
  }


    //处理选中人员值
    getChooseUids = (ids) => {
        let demoarr = "";
        if (ids.length>0) {
            for ( let i = 0; i <ids.length; i++){
                let chooseid = ids[i];
                demoarr=chooseid.replace(/[^0-9]/ig, "")+","+demoarr;

            }
        }
        return demoarr;
    }

  // 保存富文本内容
  @action
  saveOrUpdateBlog = (params,callback) => {
    if (this.type === '2') {
      params.discussId= this.discussId;
    }


      let choseidss = "";
      let chooseuuids =  params.content.match(/uuuid[\d]*uu/g);
      if(chooseuuids!=null){
           choseidss = this.getChooseUids(chooseuuids);
      }
      params.atChooseId =choseidss;

      let cs = document.getElementById('writeTitle').getAttribute('iswrite');
      if(cs=='write'){
        params.fromTag='2'; //从写微博页面发布 删除草稿
      }else {
        params.fromTag='1'; //从便签页面发布  删除标签
          params.discussId='0'; //微博追加进去
      }

  if(window.location.href.indexOf('/myBlog/blog/writeMyBlog')>0){
          params.fromTag='5';
      }

      if(params.workdate==null||params.workdate==undefined){
        params.workdate= WeaUtils.DateFormat(new Date(), 'yyyy-MM-dd');
      }


      WriteApi.saveOrUpdateBlog(params).then(res => {
      if (res.status == 1) {
         this.blogCommentStore.doOperateReply({
          replyId: this.replyComment ? this.replyComment.replyId : res.replyList[0].replyId,
          reply: res.replyList[0],
        })
        if (callback) { callback(); }
        this.blogText = null;
      }
    });
  }



    // 保存富文本内容
    @action
    saveOrUpdateBlogNote = (params,callback) => {

        let pp = {}
        let cs = document.getElementById('writeTitle').getAttribute('iswrite');

        if(cs=='write'){
         if(params.workdate==null||params.workdate==''||params.workdate==undefined){
            params.workdate==WeaUtils.DateFormat(new Date(), 'yyyy-MM-dd');
         }
         pp = {content:params.content,workdate:params.workdate}
        }else{
         pp = {content:params.content}
        }
        this.blognotes=params.content;
        if(params.isInterval=="1"){//定时保存草稿
            pp.oldContent = params.oldContent;
            pp.isInterval = params.isInterval;
            WriteApi.saveBlogNoteByInterval(pp).then(res => {
              if (callback) { callback(res); }
          });
        }else{
            WriteApi.saveBlogNote(pp).then(res => {
              if (res.status == 1) {
                  Toast.info(getLabel(22619 ,'保存成功'), 1);
              }
              if (callback) { callback(); }
                this.blogText = null;
          });

        }
       
     
       
    }




    @action
    getTimerByNote = (params, callback) => {
      WriteApi.getTimerByNote().then(res => {
        this.notetiming = res.notetiming;
        if (callback) callback(res);
      });
    }

    getIsOneSubmitInfo = (callback)=>{
      WriteApi.getIsOneSubmitInfo({}).then(result => {
          if (callback) callback(result);
      })
  }



    // 清空富文本编辑器
  clearBlogText = () => {
    this.blogText = null;
    this.type = null;
  }

  clearComment = () => {
    this.replyComment = null;
    this.replyCommentParent = null;
    this.commentReplyStoreMap = {};
  }

  @action('默认模板')
  getDefaultTemplate = (params, callback) => {
    Api.getDefaultTemplate(params).then(res=>{
      if(res.defaultTemplate && res.hasSubmit == 0){
        const defaultTemplate = Base64.decode(res.defaultTemplate.tempContent || '');
        //this.blogText = Base64.decode(res.defaultTemplate.tempContent || '');
        if (callback) callback(defaultTemplate);
      }
    })
  }

    @action
    getEcmeTemplate = (params, callback) => {
        Api.getDefaultTemplate(params).then(res=>{
                if (callback) callback(res);
        })
    }




    //获取微博草稿
    @action
    getBlogNote = (params,callback) => {

    if(params.workdate==null||params==""){
        params.workdate = WeaUtils.DateFormat(new Date(), 'yyyy-MM-dd')
    }
	
    this.workdate =  params.workdate;
    
	WriteApi.getBlogNote(params).then(res => {
		this.blognotes=Base64.decode(res.content);
        if (callback) callback(Base64.decode(res.content));
    })
    }


    @action
    getBlogBianQian = (params,callback) => {
        WriteApi.getBlogNote().then(res => {
            if (callback) callback(Base64.decode(res.content));
        })
   }

    //获取微博便签

    blogNoteDemo = () => {

        this.routePath='/myBlog/writeBlogNote';
        WriteApi.getBlogNote().then(res => {
			this.blognotes = Base64.decode(res.content);
            this.writeReply.setData({richText: Base64.decode(res.content)});
        })
    }


    attentionUserList = (params,callback) => {
      Api.attentionUserList(params).then(res => {
          if(callback)callback(res);
      })
    }


    discussShareInfo = (params,callback) => {
        Api.discussShareInfo(params).then(res => {
            if(callback)callback(res);
        })
    }


    updateBlogEcmeinfo = (params,callback) => {
        WriteApi.updateBlogEcmeinfo(params).then(res => {
           this.blogText = null;
           if(callback)callback(res);
        })
    }

    saveBlogNoteEcmeinfo = (params,callback) => {
        WriteApi.saveBlogNoteEcmeinfo(params).then(res => {
            if(callback)callback(res);
        })
    }

    saveBlogEcmeInfo = (params,callback) => {
        WriteApi.saveBlogEcmeInfo(params).then(res => {
          this.blogText = null;
          if(callback)callback(res);
        })
    }

    getBlogEcmeInfo = (params,callback) => {
        WriteApi.getBlogEcmeInfo(params).then(res => {
            if(callback)callback(res);
            }
        )
    }

}